//
//  StudentListViewController.m
//  FaceRecognition
//
//  Created by zz on 16/11/30.
//  Copyright © 2016年 Sylar. All rights reserved.
//  1.22 去掉筛选和cell上图片张数

#import "StudentListViewController.h"
#import "UploadPhotoViewController.h"
#import "ManagerInfoModel.h"
#import "StudentListTableViewCell.h"
#import "DropTable.h"

#import "ManagerPhotoListViewController.h"
#import "YiTuManagerPhotoViewController.h"
#import "YiTuUploadPhotoViewController.h"
@interface StudentListViewController ()<UISearchResultsUpdating,UITableViewDataSource,UITableViewDelegate,UISearchBarDelegate,DropTableDelgate>

@property (nonatomic,strong) UISearchController *searchController;
@property (nonatomic,strong) UITableView *tableView;

@property (nonatomic,strong) NSMutableArray * searchResults; //搜索结果数组
@property (nonatomic,strong) NSArray * studentLists; //学生数组

@property (nonatomic,strong) NSMutableArray *dataArr; //table数据源

@property (nonatomic,strong) NSMutableArray *sectionTitles;

@property (nonatomic,strong) UITextField *field;

@property (nonatomic,copy) NSString *photoCount;

@property (nonatomic,strong) UILabel *nohisLabel;

@property (nonatomic,assign) BOOL searchFlag;

@end

@implementation StudentListViewController{
    
    int count;//计数器
    
    UILocalizedIndexedCollation *_indexCollation; //索引
    
    BOOL cancelFlag; //取消按钮x+15,第一次加后不再加
}

#pragma mark -Getter

- (UITableView *)tableView{
    
    if (_tableView == nil) {
        
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, VIEW_WIDTH, SCREENHEIGH - SafeAreaTopHeight-SafeAreaBottomHeight) style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.tableFooterView = [[UIView alloc] init];
        _tableView.tableHeaderView = self.searchController.searchBar;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [_tableView addObserver:self forKeyPath:@"contentOffset" options:NSKeyValueObservingOptionNew context:nil];
        
        _tableView.mj_header = [MJRefreshHeader headerWithRefreshingBlock:^{
           
            [self Java_getAllStudentsInClass];
        }];
        
        
        self.nohisLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 150, SCREENWIDTH, 15)];
        [self.nohisLabel setFont:[UIFont systemFontOfSize:14]];
        [self.nohisLabel setText:@"暂无该宝宝信息"];
        
        if (self.manageType != 0) {
            
            [self.nohisLabel setText:@"暂无该员工信息"];
        }
        
        [self.nohisLabel setTextColor:[UIColor colorWithHexString:@"#979797"]];
        self.nohisLabel.textAlignment = NSTextAlignmentCenter;
        self.nohisLabel.hidden = YES;
        
        [_tableView addSubview:self.nohisLabel];

        
    }
    
    return _tableView;
}

- (UISearchController *)searchController{
    
    if (!_searchController) {
        
        _searchController = [[UISearchController alloc] initWithSearchResultsController:nil];
        _searchController.searchResultsUpdater = self;
        _searchController.dimsBackgroundDuringPresentation = NO;
        _searchController.searchBar.frame = CGRectMake(0, 0, 0, 44);
        _searchController.searchBar.placeholder = [NSString stringWithFormat:@"搜索%@姓名",_manageType == 0 ? @"宝宝" : @"员工"];
        _searchController.searchBar.barTintColor = [UIColor colorWithHexString:@"#EBEFF1"];
        _searchController.searchBar.tintColor = [UIColor colorWithHexString:@"#979797"];
        
        [_searchController.searchBar setValue:@"取消" forKey:@"cancelButtonText"];

        [_searchController.searchBar sizeToFit];
        
        //隐藏searchbar上下两条线
        _searchController.searchBar.backgroundImage = [UIImage imageNamed:@"information_search_bg_"];
        
        //设置放大镜图片
        [_searchController.searchBar setImage:[UIImage imageNamed:@"search_head_"] forSearchBarIcon:UISearchBarIconSearch state:UIControlStateNormal];
        
        //取出serbar的textfield
        UITextField *field = [_searchController.searchBar valueForKey:@"searchField"];
        //设置字体
        field.font = [UIFont systemFontOfSize:14];
        
        _field = field;
        //设置searchbar代理
        _searchController.searchBar.delegate = self;
    }
    
    return _searchController;
}

- (NSMutableArray *)searchResults{
    
    if (_searchResults == nil) {
        
        _searchResults = [NSMutableArray array];
        
    }
    
    return _searchResults;
}

- (NSArray *)studentLists{
    
    if (_studentLists == nil) {
        
        _studentLists = [NSArray array];
        
    }
    
    return _studentLists;
}

- (NSMutableArray *)dataArr{

    if (_dataArr == nil) {
        
        _dataArr = [NSMutableArray array];
    }
    
    return _dataArr;
}

- (NSMutableArray *)sectionTitles{

    if (_sectionTitles == nil) {
        
        _sectionTitles = [NSMutableArray array];
    }
    
    return _sectionTitles;
}

#pragma mark -LifeCycle

- (instancetype)init {
    self = [super init];
    if (self) {
        self.hidesBottomBarWhenPushed = YES;
        self.definesPresentationContext = YES;
        _photoCount = @"-1";//默认获取所有张数照片，现在去除了筛选，只有-1的情况
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    UIBarButtonItem *backItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageWithOriginalName:@"back"] style:UIBarButtonItemStyleDone target:self action:@selector(back)];
    self.navigationItem.leftBarButtonItem = backItem;

    if (_manageType == 1) {
        
        UIBarButtonItem *right = [[UIBarButtonItem alloc] initWithTitle:@"筛选" style:UIBarButtonItemStyleDone target:self action:@selector(filterAction)];
        [right setTintColor:[UIColor blackColor]];
        [right setTitleTextAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:17]} forState:UIControlStateNormal];
        self.navigationItem.rightBarButtonItem = right;
    }
    
    //员工列表，学校的名字
    if (_manageType != 0) {
        
        self.title = [SYAccountTool ShareAccount].account.scname;
    }

    [self.view addSubview:self.tableView];
    
    //获取班级下的所有学生列表
    //[self getAllStudentsInClass];
    [self Java_getAllStudentsInClass];

}

- (void)dealloc{
    
    if (count == 0) {  //count = 0 说明self.tableview还没有移除self的观察者身份
        
        [self.tableView removeObserver:self forKeyPath:@"contentOffset"];
    }
    
}

#pragma mark -KVO
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context{
    
    [self setCancelButtonColor:nil ColorString:nil];
    
}

#pragma mark -Private
- (void)Java_getAllStudentsInClass {
    
    RequestParam *param = [RequestParam param];

    param.scid = _scid;
    param.pageno = @"1";
    param.pagesize = @"10000";
    param.classid = _classid;
    param.photocounts = _photoCount;
    
    
    NSString *method = _manageType == 0?@"api/getClassStudentList":@"api/getSchoolUserList";
    
    [Utils Java_get:method parameters:param.mj_keyValues success:^(NSInteger recode, id jsonObject) {
        
        NSArray *arr = [jsonObject objectForKey:@"re_data"];
        
        if (arr.count == 0) {
            
            self.nohisLabel.hidden = NO;
            
            if (self.manageType == 0) {
                
                self.nohisLabel.text = @"暂未找到符合该条件的宝宝";
            }else if (self.manageType == 1) {
                
                self.nohisLabel.text = @"暂未找到符合该条件的员工";
            }
            
        }else{
            
            self.nohisLabel.hidden = YES;
        }
        
        self.studentLists = [ManagerInfoModel mj_objectArrayWithKeyValuesArray:arr];
        self.dataArr = [self sortDataArray:self.studentLists];
        [self.tableView reloadData];
        
        [self.tableView.mj_header endRefreshing];
        
    } failure:^(NSInteger recode, NSError *error) {
        [self showHint:error.localizedDescription];
    }];
}



//设置取消按钮背景颜色
- (void)setCancelButtonColor:(UISearchBar *)searchBar ColorString:(NSString *)colorStr{
    
    UIButton *btn = (UIButton *)[_searchController.searchBar valueForKey:@"cancelButton"];
    
    if (btn) {
        
        [btn setTitleColor:DEFAULTCOLOR forState:UIControlStateNormal];
        
        if (cancelFlag == NO) {
        
            CGFloat x = btn.frame.origin.x;
            x += 15;
        
            btn.frame = CGRectMake(x, btn.frame.origin.y, btn.frame.size.width, btn.frame.size.height);
            cancelFlag = YES;
        }
        
        //设置完后。不在观察tableView的变化
        if (count == 0) {
            
            [self.tableView removeObserver:self forKeyPath:@"contentOffset"];
            count++;
        }
    }

}

#pragma mark -按索引分区
- (NSMutableArray *)sortDataArray:(NSArray *)array{
    
    //建立索引核心
    UILocalizedIndexedCollation *indexCollation = [UILocalizedIndexedCollation currentCollation];
    _indexCollation = indexCollation;
    
    [self.sectionTitles removeAllObjects];
    [self.sectionTitles addObjectsFromArray:[indexCollation sectionTitles]];
    
    //返回27， a - z 和#
    NSInteger highSection = self.sectionTitles.count;
    
    //tableview分区
    NSMutableArray *sortedArray = [NSMutableArray arrayWithCapacity:highSection];
    for (int i = 0; i < highSection; i++) {
        
        NSMutableArray *sectionArr = [NSMutableArray arrayWithCapacity:1];
        [sortedArray addObject:sectionArr];
    }
    
    for (ManagerInfoModel *model in array) {
        
        NSString *firstLetter = model.indexname;
        
        if (firstLetter) {
            
            NSInteger section = [indexCollation sectionForObject:firstLetter collationStringSelector:@selector(uppercaseString)];
            
            NSMutableArray *arrayM = [sortedArray objectAtIndex:section];
            [arrayM addObject:model];
        }
    }
    
    //每个section内的数组排序
    for (int i = 0; i < sortedArray.count; i++) {
        NSArray *lettersArr = [[sortedArray objectAtIndex:i] sortedArrayUsingComparator:^NSComparisonResult(ManagerInfoModel*  _Nonnull obj1, ManagerInfoModel*  _Nonnull obj2) {
            
            NSString *letter1 = obj1.indexname;
            NSString *letter2 = obj2.indexname;
            
            return [letter1 caseInsensitiveCompare:letter2];
        }];
        
        [sortedArray replaceObjectAtIndex:i withObject:[NSMutableArray arrayWithArray:lettersArr]];
    }
    
    return sortedArray;
}

#pragma mark -UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return !self.searchController.isActive ? self.dataArr.count : 1;

}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    
    return !self.searchController.isActive ? [[self.dataArr objectAtIndex:section] count] : self.searchResults.count;

    
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString *cellid = @"cellid";
    StudentListTableViewCell *cell = [[StudentListTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellid];

    if (_manageType == 0) {
        
        cell.countLabel.hidden = YES;
        
    }else
    {
        cell.countLabel.hidden = NO;
    }
    
    //没有进行搜索操作的列表
    if (!self.searchController.isActive) {
        
        ManagerInfoModel *model;

        model = [[self.dataArr objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];
        
        cell.model = model;
        
    }else{  //搜索结果
    
        ManagerInfoModel *model = [self.searchResults objectAtIndex:indexPath.row];
        cell.model = model;
    }
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}


#pragma mark -UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
   
   NSString * facetype = [SYAccountTool ShareAccount].account.facetype;
   

    if(_manageType == 0)
    {
      if ([facetype isEqualToString:@"0"]) {
             
           ManagerPhotoListViewController *photoListVC = [[ManagerPhotoListViewController alloc] init];
         
           if (!self.searchController.isActive) {
              
               photoListVC.model = [[self.dataArr objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];
           }else{
              
               photoListVC.model = [self.searchResults objectAtIndex:indexPath.row];
              
           }
           [self.navigationController pushViewController:photoListVC animated:NO];
         
         }else
         {
            YiTuManagerPhotoViewController *photoListVC = [[YiTuManagerPhotoViewController alloc] init];
            
            if (!self.searchController.isActive) {
               
               photoListVC.model = [[self.dataArr objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];
            }else{
               
               photoListVC.model = [self.searchResults objectAtIndex:indexPath.row];
               
            }
            [self.navigationController pushViewController:photoListVC animated:NO];
         }
        
    }else if (_manageType == 1)
    {
       if ([facetype isEqualToString:@"0"]) {
          
           UploadPhotoViewController *uploadVC = [[UploadPhotoViewController alloc] init];
          
           if (!self.searchController.isActive) {
              
               if ([self.photoCount isEqualToString:@"-1"]) { //在分组状态下
                  
                   uploadVC.model = [[self.dataArr objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];
               }else{ //在筛选状态下
                  
                   uploadVC.model = [self.studentLists objectAtIndex:indexPath.row];
               }
              
               uploadVC.selectedCell = [tableView cellForRowAtIndexPath:indexPath];
              
           }else{
              
               uploadVC.model = [self.searchResults objectAtIndex:indexPath.row];

           }
          
           uploadVC.lastType = [SYAccountTool ShareAccount].account.lasttype;
           uploadVC.manageType = _manageType;
           [self.navigationController pushViewController:uploadVC animated:YES];
          
       }else
       {
           YiTuUploadPhotoViewController * uploadVC = [[YiTuUploadPhotoViewController alloc] init];
          
          if (!self.searchController.isActive) {
             
             if ([self.photoCount isEqualToString:@"-1"]) { //在分组状态下
                
                uploadVC.model = [[self.dataArr objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];
             }else{ //在筛选状态下
                
                uploadVC.model = [self.studentLists objectAtIndex:indexPath.row];
             }
             
             uploadVC.selectedCell = [tableView cellForRowAtIndexPath:indexPath];
             
          }else{
             
             uploadVC.model = [self.searchResults objectAtIndex:indexPath.row];
             
          }
          
          uploadVC.lastType = [SYAccountTool ShareAccount].account.lasttype;
          uploadVC.manageType = _manageType;
          [self.navigationController pushViewController:uploadVC animated:YES];
       }
    }
    
    
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    if (section == 0 && [self.dataArr[section] count] == 0) {
        
        return nil;
    }
    
    UIView *contentView = [[UIView alloc] init];
    contentView.backgroundColor = [UIColor colorWithHexString:@"#F5F8FA"];
    
    UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, -0.5, SCREENWIDTH, 0.5)];
    lineView.backgroundColor = [UIColor colorWithHexString:@"#F5F8FA"];
    [contentView addSubview:lineView];
    
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(15, 2, 100, 16)];
    label.backgroundColor = [UIColor clearColor];
    [label setText:[self.sectionTitles objectAtIndex:section]];
    label.textColor = [UIColor colorWithHexString:@"#3b3b3b"];
    label.font=[UIFont boldSystemFontOfSize:16];
    [contentView addSubview:label];
    
    //    UILabel *line=[[UILabel alloc]init];
    //    line.frame=CGRectMake(0, -0.5, 60, 0.5);
    //
    //    line.backgroundColor = [UIColor colorWithHexString:@""  ];
    //    //    [contentView addSubview:line];
    //
    //    UILabel *line2=[[UILabel alloc]initWithFrame:CGRectMake(0, 20.5, [UIScreen mainScreen].bounds.size.width, 0.5)];
    //    line2.backgroundColor = RGBACOLOR(199, 199, 204, 1);
    //    [contentView addSubview:line2];
    
    return contentView;
}

- (NSArray<NSString *> *)sectionIndexTitlesForTableView:(UITableView *)tableView{
    
    if (!self.searchController.isActive && [_photoCount isEqualToString:@"-1"]) {
        
        NSMutableArray *existsTitles = [NSMutableArray array];
        
        for (int i = 0; i < self.sectionTitles.count; i++) {
            
            if ([[self.dataArr objectAtIndex:i] count] > 0) {
                
                [existsTitles addObject:[self.sectionTitles objectAtIndex:i]];
            }
        }
        
        return existsTitles;
    }
    
    return nil;
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    if (!self.searchController.isActive) {
        
        if ([self.dataArr[section] count] == 0) {
            
            return 0;
        }
        
        if (![_photoCount isEqualToString:@"-1"]) { //删选界面不显示 a b c
            return 0;
        }
        
        return 20;
    }
    
    return 0;
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 58;
}

#pragma mark -UISearchResultsUpdating
- (void)updateSearchResultsForSearchController:(UISearchController *)searchController{
    
    searchController.searchBar.keyboardType = UIKeyboardTypeDefault;
    
    NSPredicate *pre = [NSPredicate predicateWithFormat:@"self.studentname contains[c] %@",searchController.searchBar.text];
    
    if (self.manageType != 0) { //员工列表
        
        pre = [NSPredicate predicateWithFormat:@"self.username contains[c] %@",searchController.searchBar.text];
    }
    
    
    self.searchResults = [[self.studentLists filteredArrayUsingPredicate:pre] mutableCopy];
    
    if (self.searchResults.count || searchController.searchBar.text.length == 0) {
        
        self.nohisLabel.hidden = YES;
        
    }else{
    
        self.nohisLabel.hidden = NO;
    }
    
    if (!self.searchFlag) { //取消搜索后，回走这个地方
        
        self.nohisLabel.hidden = YES;
    }
    
    [self.tableView reloadData];
}

#pragma mark -UISearchBarDelegate
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar{

    self.navigationController.navigationBar.translucent = YES;
    
    [searchBar setBarTintColor:[UIColor whiteColor]];
    searchBar.keyboardType = UIKeyboardTypeDefault;
    
    //设置取消按钮背景颜色
    [self setCancelButtonColor:nil ColorString:nil];
    
    _field.backgroundColor = [UIColor colorWithHexString:@"#EBEFF1"];
    
    self.searchFlag = YES;
}


- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar{
    
    self.navigationController.navigationBar.translucent = NO;
    
    searchBar.barTintColor = [UIColor colorWithHexString:@"#EBEFF1"];
    
    _field.backgroundColor = [UIColor whiteColor];
    
    //设置取消按钮背景颜色
    UIButton *btn = (UIButton *)[_searchController.searchBar valueForKey:@"cancelButton"];
    [btn setTitleColor:DEFAULTCOLOR forState:UIControlStateNormal];
    
    //隐藏没有没有搜索内容的提示
    self.nohisLabel.hidden = YES;
    
    self.searchFlag = NO;
}

#pragma mark -Actions
- (void)back{
    
    [self.navigationController popViewControllerAnimated:YES];
}

//按底片张数筛选学生
- (void)filterAction{
    
    DropTable *table = [[DropTable alloc] init];
    
    table.lists = @[@"全部",@"0张",@"1张",@"2张",@"3张"];
    table.delegate = self;
    
}

#pragma mark -DropTableDelegate
- (void)tableViewCellSelected:(NSInteger)index{
    
    if (index == 0) {
        
        _photoCount = @"-1";
        
    }else{
        
        _photoCount = [NSString stringWithFormat:@"%ld",index - 1];
    }
    
    [self Java_getAllStudentsInClass];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
